package me.yricky.cov_spectrum

import android.app.Application
import android.os.Handler
import com.fasterxml.jackson.databind.DeserializationFeature
import io.ktor.client.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.jackson.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.android.asCoroutineDispatcher
import me.yricky.cov_spectrum.model.UserConfig
import me.yricky.cov_spectrum.model.utils.toJson
import me.yricky.cov_spectrum.model.utils.toObject
import java.io.File
import java.net.Proxy

class App:Application() {
    private val appCoroutineScope by lazy {
        CoroutineScope(Handler(mainLooper).asCoroutineDispatcher("appScope"))
    }

    val httpClient by lazy {
        HttpClient {
            followRedirects = true
            engine {
                pipelining = true
                threadsCount = 8
                proxy = Proxy.NO_PROXY
            }

            install(ContentNegotiation) {
                jackson {
                    configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                }
            }
        }
    }

    val userCfg by lazy {
        val cfgFile = File(getExternalFilesDir("default"),"cfg.json")
        if(!cfgFile.isFile){
            cfgFile.deleteRecursively()
            cfgFile.createNewFile()
        }
        UserConfig(
            save = { cfgFile.writeText(it.toJson()) },
            load = {
                kotlin.runCatching {
                    cfgFile.readText().toObject(UserConfig.ConfigItem::class.java)
                }.getOrDefault(UserConfig.ConfigItem())
            },
            scope = appCoroutineScope
        )
    }

    override fun onCreate() {
        super.onCreate()
        app = this
        userCfg.get()
    }


}

lateinit var app:App
private set